package com.kzw.oa.comm.service;

import java.util.Calendar;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kzw.core.service.hibernate.DefaultEntityManager;
import com.kzw.oa.comm.model.SerialNumber;
import com.kzw.oa.comm.type.SnType;

@Service
@Transactional(readOnly=false)
public class SerialNumberService extends DefaultEntityManager<SerialNumber, Long> {

	/**
	 * 前缀 + 年 + 月 + 5位流水号
	 * */
	public synchronized String generateSN(SnType snType) {
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH) + 1;
		String sno;
		
		SerialNumber sn = findUniqueBy("cateKey", snType.getName());
		if(sn == null) {
			// 增加一条记录
			SerialNumber number = new SerialNumber();
			number.setCateKey(snType.getName());
			number.setMaxSn(1);
			number.setPrefix(snType.getPrefix());
			number.setYear(year);
			number.setMonth(month);
			
			saveOrUpdate(number);
			sno = snType.getPrefix() + year + StringUtils.leftPad(month+"", 2, '0') + 
					StringUtils.leftPad("1", 5, '0');
			return sno;
		}
		
		// 不是该年或该月
		if(sn.getYear()!=year || sn.getMonth()!=month) {
			sn.setYear(year);
			sn.setMonth(month);
			sn.setMaxSn(1);
			
			saveOrUpdate(sn);
			sno = sn.getPrefix() + year + StringUtils.leftPad(month+"", 2, '0') + 
					StringUtils.leftPad("1", 5, '0');
			return sno;
		}
		
		// 年月都相同，只需要更新最大流水号
		int maxSn = sn.getMaxSn();
		maxSn ++;
		sn.setMaxSn(maxSn);
		
		saveOrUpdate(sn);
		sno = sn.getPrefix() + year + StringUtils.leftPad(month+"", 2, '0') + 
				StringUtils.leftPad(maxSn+"", 5, '0');
		return sno;
	}
	

}
